from rest_framework import serializers

from apps.RouteManagement.models import Route


class RouteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Route
        fields = "__all__"


class RouteTreeSerializer(serializers.ModelSerializer):
    children = RouteSerializer(many=True, read_only=True)

    class Meta:
        model = Route
        fields = ['id', 'name', 'title', 'route', 'icon', 'is_leaf', 'app_url', 'index', 'create_time',
                  'update_time', 'parent', 'children']

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 对 children 进行排序
        representation['children'] = sorted(representation['children'], key=lambda x: x['index'])
        return representation